/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kh.pi.Playlist;

import com.kh.pi.Log.Log;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author phamt_000
 */
public class PlayList implements com.kh.pi.Interface.IPlayList{
    private List<MediaPlayer> listMedia;
    
    public PlayList(String dirHost,String dirPlaylist) throws ParserConfigurationException, SAXException, IOException, URISyntaxException{
        listMedia=new ArrayList<>();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(dirHost+dirPlaylist);

        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("media");
        for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;
                        File mediaFile= new File(new URI(dirHost+eElement.getElementsByTagName("url").item(0).getTextContent()));
                        if(mediaFile.exists()){
                            listMedia.add(new MediaPlayer(new Media(dirHost+eElement.getElementsByTagName("url").item(0).getTextContent())));
                        }
                }
        }
        //if can not get list of media or list is error load khanhhoi adv
        if(listMedia.isEmpty())
        {
            listMedia.add(new MediaPlayer(new Media(dirHost+"khanhoiAdv/khanhhoiadv.mp4")));
        }
    }
    @Override
    public List<MediaPlayer> getPlayList(){
        return listMedia;
    }
    
    public void setPlayList(List<MediaPlayer> value){
        listMedia=value;
    }
}
